import * as phaser from "phaser";
import {RatingSystem} from "../sys/rating.ts";
import {Boom} from "@/widgets/Boom.ts";
import {Ocean1Main} from "@/scenes/Ocean1Main.ts";

/**
 * 数字
 */
export class NumberBall extends phaser.Physics.Arcade.Sprite {

    id: number = -1;
    private ratingSystem: RatingSystem;

    /**
     * @param scene
     * @param ratingSystem
     * @param texture
     * @param idx 横向位置
     * @param index 具体数字
     */
    constructor(scene: phaser.Scene, ratingSystem: RatingSystem, texture: string, idx: number, index: number) {
        const start = 50
        const end = scene.cameras.main.width - (2 * start + 35);
        const sw = (end - start) / 3
        const list = [start, Math.round(start + sw), Math.round(start + 2 * sw), end]
        super(scene, list[idx], 0, texture, `num${index}`);
        this.ratingSystem = ratingSystem;
        this.setScale(1.1, 1.1);
        scene.add.existing(this);
        scene.physics.add.existing(this);
        this.setOrigin(0, 0);
        this.id = index;
    }

    /**
     * 碰撞数字，如果碰到的是目标，则反应正确，否则反应错误
     */
    overlap() {
        if (!this.active || !this.visible) return
        this.disableBody(true, true);
        if (this.targetInArray()) { // 一排中有目标数字，要么反应成功，要么反应失败
            if (this.id == this.targetNumber()) { // 反应成功
                this.ratingSystem.reactionRight(RatingSystem.NUMBER);
                this.boom('SpritesNumberRight');
            } else {
                this.ratingSystem.restrainError();
                this.boom('SpritesNumberError');
            }
        } else {
            // 一排中没有目标数字，撞击了，则抑制失败
            this.ratingSystem.restrainError();
            this.boom('SpritesNumberError');
        }
        this.exit()
    }

    private boom(texture: string) {
        new Boom(this.scene, this.x + 30, this.y, texture, `num${this.id}`, 1.0);
    }

    private targetInArray() {
        return (this.scene as Ocean1Main).targetNumberInArray;
    }

    private targetNumber() {
        return (this.scene as Ocean1Main).targetNumber - 1;
    }

    /**
     * 开始下落
     */
    start(velocity: number) {
        this.setVelocityY(velocity);
    }

    preUpdate(time: number, delta: number) {
        super.preUpdate(time, delta);
        let {height} = this.scene.cameras.main;
        if (this.y >= height + 20) {
            if (this.id == this.targetNumber() - 1) { // 目标数字自行销毁，则反应失败
                this.ratingSystem.reactionError();
            } else {

            }
            this.exit();
        }
    }

    private exit() {
        this.disableBody(true, true);
        this.destroy(true);
        if (this.body) {
            this.scene.physics.world.remove(this.body);
        }
    }
}